﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;

namespace WebsiteUI.Extensions
{
    public class CheckCode
    {
        public static byte[] CreateCheckCode(string vcode)
        {
            string[] ziti = { "Arial", "Impact", "黑体", "宋体", "楷体", "微软雅黑" };
            int width = (int)(vcode.Length * 22);
            Bitmap bmp = new Bitmap(width, 30);
            Graphics g = Graphics.FromImage(bmp);
            MemoryStream stream = new MemoryStream();
            byte[] bcodes = null;
            try
            {
                Rectangle imgRect = new Rectangle(new Point(0, 0), new Size(width, 30));
                g.Clear(Color.White);
                //LinearGradientBrush lgbrush = new LinearGradientBrush(imgRect, Color.Yellow, Color.Tomato, 45);
                g.FillRectangle(new SolidBrush(Color.White), imgRect);
                g.DrawRectangle(new Pen(Color.FromArgb(213, 219, 226), 2), imgRect);

                Random rnd = new Random((int)DateTime.Now.Ticks);

                // 画出干扰线
                Pen blackPen = new Pen(Color.Black, 1);
                for (int i = 0; i < 50; i++)
                {
                    int x = rnd.Next(bmp.Width);
                    int y = rnd.Next(bmp.Height);
                    if (i % 2 == 0)
                        g.DrawLine(blackPen, x, y, x + 3, y);
                    else
                        g.DrawLine(blackPen, x, y, x + 2, y);
                }
                //在这里画一条粗线  
                //------begin
                int xx = rnd.Next(bmp.Width);
                int y1 = rnd.Next(bmp.Height);
                int y2 = rnd.Next(bmp.Height);
                Pen blackPen2 = new Pen(Color.Black, 2);
                g.DrawLine(blackPen2, xx, y1, xx + 85, y2);
                //-------------- end

                for (int i = 0; i < vcode.Length; i++)
                {
                    int zitiIndex = rnd.Next(0, ziti.Count());

                    Font font = new Font(ziti[zitiIndex], 18, FontStyle.Regular);
                    Brush brush = new SolidBrush(RandNumSupplier.GetRandomColor());
                    Matrix matrix = new Matrix();
                    float angle = rnd.Next(-20, 20);
                    matrix.RotateAt(angle, new PointF(i * 20, 4));  // 旋转字体
                    g.Transform = matrix;
                    g.DrawString(vcode[i].ToString(), font, brush, i * 20, 3);
                }

                bmp.Save(stream, ImageFormat.Jpeg);
                bcodes = stream.ToArray();
            }
            finally
            {
                g.Dispose();
                bmp.Dispose();
                stream.Close();
                stream.Dispose();
            }
            return bcodes;
        }
    }
}